import { Router, RouteRecordRaw } from 'vue-router'
const _modules = import.meta.glob('/src/views/**/*.vue')
const filterAsyncRoutes = (routes: Array<RouterType>): Array<RouteRecordRaw> => {
  //对后端返回的路由进行格式转换
  return routes!.map((route: RouterType) => {
    let obj: RouteRecordRaw = { ...route } as RouteRecordRaw
    if (route.redirect) {
      obj.redirect = route.redirect
    }
    if (route.component) {
      obj.component = _modules[`/src/views/${route.component}`]
      if (!obj!.component) {
        ElMessage({
          showClose: true,
          message: `请检查在src/views/路径是否存在${route.component}文件`,
          type: 'error'
        })
      }
    }
    if (route?.children?.length) {
      obj.children = filterAsyncRoutes(route.children as Array<RouterType>)
    }
    return obj
  })
}
export const _addRoutes = (asyncRoutes: Array<RouterType>, router: Router) => {
  const routes = filterAsyncRoutes(asyncRoutes!)
  routes!.forEach((route: RouteRecordRaw) => {
    if (!router.hasRoute(route.name!)) {
      router.addRoute('Home', route) //需要使用vue-devtools才能看到是否添加成功
    }
  })
}
//退出登录时用于清除router中的添加进的路由
export const _resetRouter = (asyncRoutes: Array<RouterType>, router: Router) => {
  asyncRoutes.forEach((route: RouterType) => {
    route.name && router.removeRoute(route.name)
  })
}
